package other.xsy.passlys.receivable;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEvent;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventRequest;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventResponse;
import com.rkhd.platform.sdk.data.model.Booking__c;
import com.rkhd.platform.sdk.data.model.Debooking__c;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.passlys.util.HCXObjectService;
import other.xsy.passlys.util.HcUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 计算订单的booking金额
 * @Author 黎炎松
 * 2024-08-14 17:02
 */
public class CalcOrderBookingAmount implements Trigger, AutoFlowEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "新增、编辑、删除重新计算订单的Booking金额 ==> ";

    /**
     * trigger 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + "触发开始");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<XObject> objectList = new ArrayList<>();
        for (XObject xObject : dataList) {
            objectList.add(xObject);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        Long orderId = objectList.get(0).getAttribute("order__c");
        dealOrderBookingAmount(orderId);
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * autoFlow 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public AutoFlowEventResponse execute(AutoFlowEventRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + "自动流程触发开始：" + request.getDataId());
        try {
            Booking__c booking = new Booking__c();
            booking.setId(request.getDataId());
            booking = hcxObjectService.get(booking);
            dealOrderBookingAmount(booking.getOrder__c());
        } catch (ApiEntityServiceException e) {
            throw new RuntimeException(e);
        }
        AutoFlowEventResponse response = new AutoFlowEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    public static void main(String[] args) throws Exception {
        CalcOrderBookingAmount calcOrderBookingAmount = new CalcOrderBookingAmount();
        calcOrderBookingAmount.dealOrderBookingAmount(3512174804834969L);
    }

    /**
     * 处理订单的booking金额
     * @param orderId
     */
    public void dealOrderBookingAmount(Long orderId) {
        try {
            logger.info(LOGGER_MSG + "开始处理");
            // 查询当前 contractAmountTZA__c: 合同额（含税台账）(原币) customItem69__c:合同额（不含税）(原币) bookingType__c: Booking 类型  1：booking 2:deBooking
            String sql = String.format("select id,order__c,contractAmountTZA__c,customItem69__c,bookingType__c from booking__c " +
                    "where order__c = %s order by createdAt", orderId);
            List<Booking__c> bookingList = hcxObjectService.query(sql, Booking__c.class);
            System.out.println("bookingList = " + bookingList);

            // 对金额进行汇总
            double taxAmount = 0; // 含税
            double noTaxAmount = 0; // 不含税
            for (Booking__c bookingObj : bookingList) {
                taxAmount = HcUtils.bgAdd(taxAmount, bookingObj.getContractAmountTZA__c() != null ? bookingObj.getContractAmountTZA__c() : 0);
                noTaxAmount = HcUtils.bgAdd(noTaxAmount, bookingObj.getCustomItem69__c() != null ? bookingObj.getCustomItem69__c() : 0);
            }
            logger.info(LOGGER_MSG + "taxAmount: " + taxAmount);
            logger.info(LOGGER_MSG + "noTaxAmount: " + noTaxAmount);

            // 更新订单金额
            Order order = new Order();
            order.setId(orderId);
            order.setBookingTax__c(taxAmount);
            order.setBookingNoTax__c(noTaxAmount);
            hcxObjectService.update(order);

            logger.info(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            logger.error(LOGGER_MSG + "处理异常: " + e.getMessage());
        }
    }



}
